<?php

class ApiController extends Controller {
    public function  actionGetAllCompanies() {

        $connection = Yii::app()->db;
        $query = "select * from company where published = 1 limit 10";

        $command = $connection->createCommand($query);
        $results = $command->queryAll();

        if (count($results) > 0) {
            return $this->_response(array('companies' => $results, 'success' => 1));
        } else {
            return $this->_response(array('message' => "Không tìm thấy công ty", 'success' => 0));
        }
    }

    public function  actionGetAllCategories() {
        $connection = Yii::app()->db;
        $query = "select * from category limit 2";

        $command = $connection->createCommand($query);
        $results = $command->queryAll();

        if (count($results) > 0) {
            return $this->_response(array('categories' => $results, 'success' => 1));
        } else {
            return $this->_response(array('message' => "Không tìm thấy danh mục", 'success' => 0));
        }
    }

    public function actionCreateCompany() {
        $src = dirname(Yii::getPathOfAlias('application')) . '/create_company_android_log.txt';

        $name = isset($_POST["name"]) ? $_POST["name"] : "";
        $owner = isset($_POST["owner"]) ? $_POST["owner"] : "";
        $address = isset($_POST["address"]) ? $_POST["address"] : "";
        $city = isset($_POST["city"]) ? $_POST["city"] : "";
        $phone = isset($_POST["phone"]) ? $_POST["phone"] : "";
        $category_str = isset($_POST["category"]) ? $_POST["category"] : 0;
        $category_str = str_replace('&amp;', '&', $category_str);

        $old_content = file_get_contents($src);

        $category = Category::model()->findByAttributes(array('name_vn' => $category_str));

        if ($category == null) {
            $new_content = $old_content . "\n" . "fail; $category_str" . date('d-m-Y h:i:s') . ";\r\n";
            $cache_file = fopen($src, 'w');
            fwrite($cache_file, $new_content);
            fclose($cache_file);
        }

        $company = new Company();
        $company->name = $name;
        $company->owner = $owner;
        $company->address = $address;
        $company->city = $city;
        $company->phone = $phone;
        $company->category_id = $category->id;
        $company->picture = '/pictures/no-image.png';

        if ($company->save()) {
            $new_content = $old_content . "\n" . "succeed;" . date('d-m-Y h:i:s') . ";\r\n";
            $cache_file = fopen($src, 'w');
            fwrite($cache_file, $new_content);
            fclose($cache_file);
        } else {

            $errors = $company->getErrors();
            $content = '';
            foreach ($errors as $error) {
                $content .= $error['message'] . ' ; ';
            }

            $new_content = $old_content . "\n" . "fail;$content" . ';' . date('d-m-Y h:i:s') . ";\r\n";
            $cache_file = fopen($src, 'w');
            fwrite($cache_file, $new_content);
            fclose($cache_file);
        }

    }

    public function actionGetCompaniesNearBy() {
        if (!isset($_GET['lat']) || !isset($_GET['lng'])) return $this->_response(array('success' => 0));

        $lat = isset($_GET['lat']) ? $_GET['lat'] : 0;
        $lng = isset($_GET['lng']) ? $_GET['lng'] : 0;

        $cur_lat = isset($_GET['cur_lat']) ? $_GET['cur_lat'] : 0;
        $cur_lng = isset($_GET['cur_lng']) ? $_GET['cur_lng'] : 0;

        $calculate = isset($_GET['calculate']) ? $_GET['calculate'] : 0;
        $connection = Yii::app()->db;

        $lng_point = end(array_filter(explode('.', $lng)));
        $lat_point = end(array_filter(explode('.', $lat)));

        $small_lng = intval(floor($lng)) - 1 + floatval('0.' . ($lng_point));
        $small_lat = intval(floor($lat)) - 1 + floatval('0.' . ($lat_point));

        $big_lng = floatval($small_lng) + 3;
        $big_lat = floatval($small_lat) + 3;

        $query = "select t.id,t.lng,t.lat,t.name,t.owner,t.address,t.category_id,t.picture,t.city,t.phone,t.zipcode,(
                    ROUND(( 3959 * acos( cos( radians($lat) ) *
                    cos( radians( t.lat ) ) *
                    cos( radians( t.lng ) -
                    radians($lng) ) +
                    sin( radians($lat) ) *
                    sin( radians( t.lat ) ) ) ) ,2)+0.2 )
                    AS distance
            from company t
            inner join category c on c.id = t.category_id
            where t.published = 1  and (t.lng > {$small_lng} and t.lng < {$big_lng}) and (t.lat > {$small_lat} and t.lat < {$big_lat})
             order by distance ASC
            limit 50

        ";

        $command = $connection->createCommand($query);
        $results = $command->queryAll();

        if ($calculate && $cur_lat != 0 && $cur_lng != 0) {
            $results = $this->calculateDistance($results, $cur_lat, $cur_lng);
        }

        $ads = array();
        if (count($results) > 0) {
            $zipcode = $results[0]['zipcode'];
            $ads = Yii::app()->db->createCommand("SELECT * FROM advertise a WHERE a.zipcode = '{$zipcode}' and published = 1 order by id DESC limit 1 ")->queryAll();;
        }

        return $this->_response(array(
            'success' => 1,
            'companies' => $results,
            'cur_lat' => $lat,
            'cur_lng' => $lng,
            'ads' => $ads
        ));
    }

    private function  calculateDistance($results, $cur_lat, $cur_lng) {
        $connection = Yii::app()->db;
        $arr = array();
        foreach ($results as $item) {
            $id = $item['id'];
            $query = "select t.id,t.lng,t.lat,t.name,t.owner,t.address,t.category_id,t.picture,t.city,t.phone,t.zipcode,(
                    ROUND(( 3959 * acos( cos( radians($cur_lat) ) *
                    cos( radians( t.lat ) ) *
                    cos( radians( t.lng ) -
                    radians($cur_lng) ) +
                    sin( radians($cur_lat) ) *
                    sin( radians( t.lat ) ) ) ) ,2)+0.2 )
                    AS distance
            from company t
            inner join category c on c.id = t.category_id
            where t.id = {$id}
             order by distance ASC
            limit 1
        ";

            $command = $connection->createCommand($query);
            $company = $command->queryRow();
            array_push($arr, array(
                'id' => $company["id"],
                'name' => $company["name"],
                'owner' => $company["owner"],
                'address' => $company["address"],
                'city' => $company["city"],
                'phone' => $company["phone"],
                'lng' => $company["lng"],
                'lat' => $company["lat"],
                'zipcode' => $company["zipcode"],
                'distance' => $company["distance"],
            ));
        }

        function distance_sort($a, $b) {
            $a = $a['distance'];
            $b = $b['distance'];
            if ($a == $b)
                return 0;
            return ($a > $b) ? 1 : -1;
        }

        usort($arr, "distance_sort");

        return $arr;
    }

    public function actionSearchCompany() {
        if (!isset($_GET['keywords'])) return;

        $lng = isset($_GET['lng']) ? $_GET['lng'] : '';
        $lat = isset($_GET['lat']) ? $_GET['lat'] : '';

        $keywords = (trim($_GET['keywords']));
        $name_keywords = "%$keywords%";
        $phone_keywords = str_replace(' ', '-', $keywords);
        $connection = Yii::app()->db;
        $is_utf8 = HSCommon::detectUTF8($keywords);
        $results = array();
        if ($is_utf8) {

            if ($lng == '' && $lat == '') {
                $query = "
                    select *
                    from company c
                    where c.published = 1  and (lower(c.name) like LOWER('{$name_keywords}') collate utf8_bin or c.phone like '{$phone_keywords}' )
                    limit 50";
            } else {
                $query = "
                    select *,  (
                        ROUND(( 3959 * acos( cos( radians($lat) ) *
                                cos( radians( c.lat ) ) *
                                cos( radians( c.lng ) -
                                    radians($lng) ) +
                                sin( radians($lat) ) *
                                sin( radians( c.lat ) ) ) ) ,2)+0.2 )
                        AS distance

                    from company c
                    where c.published = 1  and (lower(c.name) like LOWER('{$name_keywords}') collate utf8_bin or c.phone like '{$phone_keywords}' )
                    order by distance ASC
                    limit 50
        ";
            }

            $command = $connection->createCommand($query);
            $results = $command->queryAll();

        }
        if (count($results) == 0 || !$is_utf8) {

            if ($lng == '' && $lat == '') {
                $query = "
                    select *
                    from company c
                    where c.published = 1  and (lower(c.name) like LOWER('{$name_keywords}') or c.phone like LOWER('{$phone_keywords}') )
                    limit 50";
            } else {
                $query = "
                    select *,(
                        ROUND(( 3959 * acos( cos( radians($lat) ) *
                                cos( radians( c.lat ) ) *
                                cos( radians( c.lng ) -
                                    radians($lng) ) +
                                sin( radians($lat) ) *
                                sin( radians( c.lat ) ) ) ) ,2)+0.2 )
                        AS distance

                    from company c
                    where c.published = 1  and (lower(c.name) like LOWER('{$name_keywords}') or c.phone like LOWER('{$phone_keywords}') )
                    order by distance ASC
                    limit 50";
            }

            $command = $connection->createCommand($query);
            $results = $command->queryAll();
        }

        $ads = array();
        if (count($results) > 0) {
            $zipcode = $results[0]['zipcode'];
            $ads = Yii::app()->db->createCommand("SELECT * FROM advertise a WHERE a.zipcode = '{$zipcode}' and published = 1  order by id DESC limit 1")->queryAll();;
        }

        return $this->_response(array(
            'success' => 1,
            'companies' => $results,
            'many' => count($results) > 1,
            'ads' => $ads));

    }

    public function actionGetCompaniesByZipCode() {
        if (!isset($_GET['keywords'])) return;

        $lat = isset($_GET['lat']) ? $_GET['lat'] : 0;
        $lng = isset($_GET['lng']) ? $_GET['lng'] : 0;
        $zipcode = (trim($_GET['keywords']));

        $connection = Yii::app()->db;

        $query = "select t.id,t.lng,t.lat,t.name,t.owner,t.address,t.category_id,t.picture,t.city,t.phone,t.zipcode,(
                    ROUND(( 3959 * acos( cos( radians($lat) ) *
                    cos( radians( t.lat ) ) *
                    cos( radians( t.lng ) -
                    radians($lng) ) +
                    sin( radians($lat) ) *
                    sin( radians( t.lat ) ) ) ) ,2)+0.2 )
                    AS distance
            from company t
            inner join category c on c.id = t.category_id
            where t.published = 1  and t.zipcode = {$$zipcode}
             order by distance ASC";

        $command = $connection->createCommand($query);
        $results = $command->queryAll();

        $ads = array();
        if (count($results) > 0) {
            $ads = Yii::app()->db->createCommand("SELECT * FROM advertise a WHERE a.zipcode = '{$zipcode}' and published = 1  order by id DESC limit 1")->queryAll();;
        }

        return $this->_response(array(
            'success' => 1,
            'companies' => $results,
            'many' => count($results) > 1,
            'ads' => $ads));
    }

    public function actionGetAdByZipcode() {
        if (!isset($_GET['id'])) return;
        if (!isset($_GET['zipcode'])) return;

        $id = $_GET['id'];
        $zipcode = $_GET['zipcode'];
        $ads = Yii::app()->db->createCommand("SELECT * FROM advertise a WHERE a.id < '{$id}' and a.zipcode = '{$zipcode}' order by id DESC")->queryAll();;

        return $this->_response(array(
            'success' => 1,
            'ads' => $ads));

    }

    public function actionCreateAdvertise() {
        $src = dirname(Yii::getPathOfAlias('application')) . '/create_ad_android_log.txt';

        $title = isset($_POST["title"]) ? $_POST["title"] : "";
        $content = isset($_POST["content"]) ? $_POST["content"] : "";
        $zip_code = isset($_POST["zip_code"]) ? $_POST["zip_code"] : "";
        $category_str = isset($_POST["category"]) ? $_POST["category"] : 0;
        $category_str = str_replace('&amp;', '&', $category_str);
        $phone = isset($_POST["phone"]) ? $_POST["phone"] : 0;

        $old_content = file_get_contents($src);
        $category = AdCategory::model()->findByAttributes(array('name' => $category_str));

        if ($category == null) {
            $new_content = $old_content . "\n" . "fail; $category_str" . date('d-m-Y h:i:s') . ";\r\n";
            $cache_file = fopen($src, 'w');
            fwrite($cache_file, $new_content);
            fclose($cache_file);
            return;
        }

        $ad = new Advertise();
        $ad->title = $title;
        $ad->content = $content;
        $ad->zipcode = $zip_code;
        $ad->category_id = $category->id;
        $ad->published = 0;
        $ad->phone = $phone;
        $ad->created_date = time();

        if ($ad->save()) {
            $new_content = $old_content . "\n" . "succeed;" . date('d-m-Y h:i:s') . ";\r\n";
            $cache_file = fopen($src, 'w');
            fwrite($cache_file, $new_content);
            fclose($cache_file);
        } else {

            $new_content = $old_content . "\n" . "fail;" . date('d-m-Y h:i:s') . ";\r\n";
            $cache_file = fopen($src, 'w');
            fwrite($cache_file, $new_content);
            fclose($cache_file);
        }

    }

    public function actionGetCompany() {
        if (!isset($_GET['id'])) return;

        $connection = Yii::app()->db;
        $id = $_GET['id'];
        $query = "select c.*,cat.name_vn as category_name from company c
         inner join category cat on cat.id = c.category_id where c.id = {$id} and published = 1";

        $command = $connection->createCommand($query);
        $results = $command->queryAll();

        if (count($results) > 0) {
            return $this->_response(array('companies' => $results, 'success' => 1));
        } else {
            return $this->_response(array('message' => "Không tìm thấy công ty", 'success' => 0));
        }
    }

    public function  actionGetLatestComments() {
        if (!isset($_GET["company_id"])) return;

        $connection = Yii::app()->db;
        $id = $_GET['company_id'];
        $query = "select id,username,content,created_time from comment where company_id = {$id} and published = 1 order by id DESC limit 2";

        $command = $connection->createCommand($query);
        $results = $command->queryAll();

        $arr = array();
        foreach ($results as $item) {
            $arr[] = array(
                'id' => $item['id'],
                'name' => $item['username'],
                'content' => $item['content'],
                'created_date' => HSCommon::calculateTime($item['created_time'])
            );
        }

        if (count($results) > 0) {
            return $this->_response(array('comments' => $arr, 'success' => 1));
        } else {
            return $this->_response(array('message' => "Chưa có bình luận", 'success' => 0));
        }
    }

    public function  actionGetAllComments() {
        if (!isset($_GET["company_id"])) return;

        $connection = Yii::app()->db;
        $id = $_GET['company_id'];
        $query = "select id,username,content,created_time from comment where company_id = {$id} and published = 1 order by id DESC";

        $command = $connection->createCommand($query);
        $results = $command->queryAll();

        $arr = array();
        foreach ($results as $item) {
            $arr[] = array(
                'id' => $item['id'],
                'name' => $item['username'],
                'content' => $item['content'],
                'created_date' => HSCommon::calculateTime($item['created_time'])
            );
        }
        if (count($results) > 0) {
            return $this->_response(array('comments' => $arr, 'success' => 1));
        } else {
            return $this->_response(array('message' => "Chưa có bình luận", 'success' => 0));
        }
    }

    public function actionCreateComment() {
        $src = dirname(Yii::getPathOfAlias('application')) . '/create_comment_android_log.txt';

        $name = isset($_POST["name"]) ? $_POST["name"] : "";
        $content = isset($_POST["content"]) ? $_POST["content"] : "";
        $email = isset($_POST["email"]) ? $_POST["email"] : "";
        $company_id = isset($_POST["company_id"]) ? $_POST["company_id"] : 0;

        $old_content = file_get_contents($src);

        $comment = new Comment();
        $comment->username = $name;
        $comment->email = $email;
        $comment->content = $content;
        $comment->company_id = $company_id;
        $comment->published = 0;
        $comment->created_time = time();
        $comment->parent_id = 0;
        $comment->like_count = 0;

        if ($comment->save()) {
            $new_content = $old_content . "\n" . "succeed;" . date('d-m-Y h:i:s') . ";\r\n";
            $cache_file = fopen($src, 'w');
            fwrite($cache_file, $new_content);
            fclose($cache_file);
        } else {

            $new_content = $old_content . "\n" . "fail;" . date('d-m-Y h:i:s') . ";\r\n";
            $cache_file = fopen($src, 'w');
            fwrite($cache_file, $new_content);
            fclose($cache_file);
        }

    }

    public function actionEditCompany() {
        $src = dirname(Yii::getPathOfAlias('application')) . '/edit_company_android_log.txt';

        $name = isset($_POST["name"]) ? $_POST["name"] : "";
        $owner = isset($_POST["owner"]) ? $_POST["owner"] : "";
        $address = isset($_POST["address"]) ? $_POST["address"] : "";
        $city = isset($_POST["city"]) ? $_POST["city"] : "";
        $phone = isset($_POST["phone"]) ? $_POST["phone"] : "";
        $category_str = isset($_POST["category"]) ? $_POST["category"] : 0;
        $category_str = str_replace('&amp;', '&', $category_str);
        $company_id = isset($_POST["company_id"]) ? $_POST["company_id"] : "";

        $old_content = file_get_contents($src);

        $category = Category::model()->findByAttributes(array('name_vn' => $category_str));

        if ($category == null) {
            $new_content = $old_content . "\n" . "fail; $category_str" . date('d-m-Y h:i:s') . ";\r\n";
            $cache_file = fopen($src, 'w');
            fwrite($cache_file, $new_content);
            fclose($cache_file);
        }

        $company = new EditCompany();
        $company->name = $name;
        $company->owner = $owner;
        $company->address = $address;
        $company->city = $city;
        $company->phone = $phone;
        $company->category_id = $category->id;
        $company->company_id = $company_id;
        $company->picture = '/pictures/no-image.png';

        if ($company->save()) {
            $new_content = $old_content . "\n" . "succeed;" . date('d-m-Y h:i:s') . ";\r\n";
            $cache_file = fopen($src, 'w');
            fwrite($cache_file, $new_content);
            fclose($cache_file);
        } else {
            $company->validate();
            $errors = $company->getErrors();
            $content = '';
            foreach ($errors as $error) {
                $new_content = $old_content . "\n" . "fail adas;" . date('d-m-Y h:i:s') . ";\r\n";
                $cache_file = fopen($src, 'w');
                fwrite($cache_file, $new_content);
                fclose($cache_file);
            }

            $new_content = $old_content . "\n" . "fail" . ';' . date('d-m-Y h:i:s') . ";\r\n";

            $cache_file = fopen($src, 'w');
            fwrite($cache_file, $new_content);
            fclose($cache_file);
        }

    }
}